package com.atguigu.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.PayVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.awt.*;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

@Controller
@Slf4j
public class OrderWebController {

    @Autowired
    OrderService orderService;
    @Autowired
    AlipayTemplate alipayTemplate;
    @GetMapping("/toTrade")
    public String toTrade( Model model) throws ExecutionException, InterruptedException {
        //确认订单业务操作
        OrderConfirmVo data =  orderService.confirmOrder();
        model.addAttribute("confirmOrderData",data);

        System.out.println(data);
        return "confirm";
    }
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
        if (responseVo.getCode()==0) {
        model.addAttribute("submitOrderResponseVo",responseVo);
            System.out.println();
        return "pay";
        }else {
            String msg="下单失败";
            switch (responseVo.getCode()){
                case 1: msg+="订单信息过期,请刷新再次提交"; break;
                case 2: msg+="订单商品价格发生变化，请确认后再次提交"; break;
                case 3: msg+="库存锁定失败，商品库存不足";    break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.mall.com/toTrade";
        }
    }
    @GetMapping(value = "/aliPayOrder",produces = "text/html")
    @ResponseBody
    public String payOrder(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
        PayVo payVo = orderService.getOrderPay(orderSn);
        String pay = alipayTemplate.pay(payVo);
        return pay;
    }
}
